package com.lemon.mybatisplus.config;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.lemon.mybatisplus.handler.MultiTenantHandler;
import com.lemon.mybatisplus.properties.MybatisPlusConfigProperties;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author 李猛
 * @datetime 2023/10/7 15:03
 * @description 类对象
 */
@Configuration
@MapperScan(value = "com.lemon.*.dao")
@AutoConfigureAfter(MybatisPlusConfigProperties.class)
public class MybatisPlusConfiguration {
    @Resource
    private MybatisPlusConfigProperties properties;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        //乐观锁配置
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        //多租户配置
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new MultiTenantHandler(properties)));

        //分页配置
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        //Mybatis-Plus配置
        return configuration -> {
            configuration.getTypeAliasRegistry().registerAliases(properties.getTypeAliasesPackage());
            configuration.getMapperRegistry().addMappers(properties.getTypeAliasesPackage());
            configuration.setMapUnderscoreToCamelCase(true);
            configuration.setLogImpl(StdOutImpl.class);
        };
    }

    @Bean
    public GlobalConfig globalConfig() {
        //全局配置
        GlobalConfig config = new GlobalConfig();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        //配置主键ID
        dbConfig.setIdType(IdType.ASSIGN_ID);
        config.setDbConfig(dbConfig);
        return config;
    }
}
